package com.yc;

import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 因为直接用socket开发客户端比较麻烦， => jdk提供了更高级的工具类
 * @program: concurrent
 * @description:
 * @author: zy
 * @create: 2022-01-15 09:07
 */
public class Test8_url_urlconnection_httpurlconnection {

    private static Logger log= Logger.getLogger(   Test8_url_urlconnection_httpurlconnection.class.getName() );

    public static void main(String[] args) throws IOException {
        //1. URL类: URL: 统一资源定位符.  + URLConnection
//        URL url=new URL( "http://www.baidu.com");
//        URLConnection con=url.openConnection();
//
//        String contentType=con.getContentType();
//        long conlength= con.getContentLength();
//        log.info(   contentType +"\t"+ conlength);
//
//        //响应头没有, 响应头的内容已经被 解析变成了  con中的属性值
//
//        InputStream iis= con.getInputStream();
//
//        byte[] bs = new byte[10 * 1024];
//        ByteArrayOutputStream baos=new ByteArrayOutputStream();
//        int length = -1;
//        while (   (length = iis.read(bs, 0, bs.length)) != -1) {
//           baos.write(bs,0,length);
//        }
//        baos.flush();
//
//        byte[] bb=baos.toByteArray();
//
//        String str = new String(bb);
//        System.out.println(str);   // 响应头    响应实体( html )

            //URL+HTTPURLConnection
        URL url=new URL( "http://www.hyycinfo.com/");
        HttpURLConnection con= (HttpURLConnection) url.openConnection();
        //HTTPURLConnection是专门针对HTTP协议，所以有很多http相关的属性
        con.setRequestProperty("HOST","www.hyycinfo.com");
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent",  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");

        con.setDoInput(   true );
        con.setDoOutput(true);

        String contentType=con.getContentType();
        long conlength=con.getContentLengthLong();
        log.info(   contentType +"\t"+ conlength);


        InputStream iis= con.getInputStream();

        byte[] bs = new byte[10 * 1024];
        int length = -1;
        ByteArrayOutputStream   baos=new ByteArrayOutputStream( );
        while (   (length = iis.read(bs, 0, bs.length)) != -1) {
           baos.write(bs,0,length);
        }
        baos.flush();

        byte[] bb=baos.toByteArray();

        String str = new String(bb);
        System.out.println(str);   // 响应头    响应实体( html )


    }
}
